﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

// 植物、僵尸 父类
public abstract class CreatureInScene
{
    // 动态数据
    protected CreatureDynamicData _dynamicData;
    // 静态数据
    protected CreatureTableData _tableData;

    protected Transform _modelRoot;
    public Transform Root { get { return _modelRoot; } }

    protected Animator _ani;

    // 挂载点
    protected Transform HitPoint { get; private set; }
    protected Transform Bottom { get; private set; }

    public virtual void InitData(CreatureTableData tableData, CreatureDynamicData dynamicData)
    {
        _tableData = tableData;

        _dynamicData = dynamicData;
        _dynamicData.MaxHP = _tableData.HP;
        _dynamicData.HP = _dynamicData.MaxHP;
    }

    // 对模型进行统一处理
    protected void initModel(Transform modelRoot)
    {
        var shadow = ResMgr.instance.InstanceGameObject("FightScene/Shadow");
        Bottom = modelRoot.Find("Bottom");
        shadow.transform.SetParent(Bottom, false);
        HitPoint = modelRoot.Find("HitPoint");

        var creature = modelRoot.gameObject.AddComponent<Creature>();
        creature.Owner = this;

        _ani = modelRoot.GetComponent<Animator>();
    }

    protected void playAni(int aniID)
    {
        _ani.SetInteger("MotionType", aniID);
    }

    protected int getAniID()
    {
        return _ani.GetInteger("MotionType");
    }

    // 播放动画
    protected void onPlayAni(int aniID)
    {
        playAni(aniID);
    }

    // 停止播放动画
    protected void onEndAni(int aniID)
    {
        if (getAniID() == aniID)
        {
            playAni(0);
        }
    }

    // 是否能被attacker攻击
    public virtual bool CanBeAttackBy(CreatureInScene attacker)
    {
        if (attacker == this) { return false; }

        return true;
    }

    // 被击中后，掉血。或者根据自己的状态单独判断
    public virtual void BeHit(int damage, int flyObjID)
    {
        var oldHp = _dynamicData.HP;
        _dynamicData.HP -= damage;
        _dynamicData.HP = Mathf.Max(0, _dynamicData.HP);

        if (oldHp > 0 && _dynamicData.HP <= 0)
        {
            onDie();
        }

        var hitObj = ResMgr.instance.InstanceGameObject("FightScene/Bullet/PeaBulletHit");
        hitObj.transform.position = HitPoint.position;
        GameObject.Destroy(hitObj, 0.2f);
    }

    protected virtual void onDie()
    {

    }
}

